package com.forlove.app.qselect.index.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseTakePhotoActivity;
import com.forlove.app.common.utils.MyTimeUtils;
import com.forlove.app.common.utils.StringUtils;
import com.forlove.app.common.widget.CircleImageView;
import com.forlove.app.manager.CustomHelper;
import com.forlove.app.manager.DataManager;
import com.forlove.app.manager.NetworkManager;
import com.forlove.app.manager.ServerManager;
import com.forlove.app.manager.UserManager;
import com.forlove.app.manager.async.LoadUserinfoAsync;
import com.forlove.app.qselect.index.presenter.ChangeMineInfoPresenter;
import com.forlove.app.qselect.index.view.ChangeMineInfoView;
import com.forlove.app.qselect.login.entity.DataDto;
import com.forlove.app.qselect.login.entity.DataInfoEntity;
import com.forlove.app.qselect.login.entity.EmotionEntity;
import com.forlove.app.qselect.login.entity.GroupEntity;
import com.forlove.app.qselect.login.entity.ProvinceEntity;
import com.forlove.app.qselect.login.entity.SchoolDto;
import com.forlove.app.qselect.login.entity.SchoolInfoEntity;
import com.forlove.app.qselect.login.entity.UserEntity;
import com.forlove.app.qselect.login.widget.ChoicePictureDialog;
import com.forlove.app.qselect.login.widget.pickerview.OptionsPickerView;
import com.forlove.app.qselect.school.ui.SearchSchoolActivity;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.TResult;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * 编辑个人资料
 * Created by yjl on 2017/11/21.
 */

public class ChangeMineInfoActivity extends BaseTakePhotoActivity implements
        ChangeMineInfoView, View.OnClickListener,
        LoaderManager.LoaderCallbacks<DataDto> {
    private final int pos_sex = 1;
    private final int pos_group = 2;
    private final int pos_emotion = 3;
    private final int pos_city = 4;
    private final int pos_age = 5;
    private final int pos_school = 6;
    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.toolbar_title)
    TextView toolbar_title;

    @BindView(R.id.image_circle_photo)
    CircleImageView image_circle_photo;

    @BindView(R.id.text_photo)
    TextView text_photo;

    @BindView(R.id.edit_user_account)
    AppCompatEditText edit_user_account;

    @BindView(R.id.edit_real_name)
    AppCompatEditText edit_real_name;

    @BindView(R.id.text_sex)
    TextView text_sex;//性别

    @BindView(R.id.view_set_sex)
    RelativeLayout view_set_sex;

    @BindView(R.id.view_set_birth)
    RelativeLayout view_set_birth;

    @BindView(R.id.text_birthday)
    TextView text_birthday;

    @BindView(R.id.view_set_emotion)
    RelativeLayout view_set_emotion;

    @BindView(R.id.text_emotion)
    TextView text_emotion;

    @BindView(R.id.view_set_address)
    RelativeLayout view_set_address;

    @BindView(R.id.text_address)
    TextView text_address;

    @BindView(R.id.view_set_grade)
    RelativeLayout view_set_grade;

    @BindView(R.id.text_grade)
    TextView text_grade;

    @BindView(R.id.view_set_school)
    RelativeLayout view_set_school;

    @BindView(R.id.text_school)
    TextView text_school;

    @BindView(R.id.line_grade)
    View line_grade;

    @BindView(R.id.button_commit)
    AppCompatButton button_commit;

    private ChangeMineInfoPresenter changeMineInfoPresenter;
    private UserEntity userEntity; //用户信息
    private ChoicePictureDialog choicePictureDialog;
    private String photoPath = "";
    private String tempPhoto = "";
    private List<String> sexList = new ArrayList<>();//性别
    private ArrayList<Integer> mYearsList = new ArrayList<>();  //年
    private List<ProvinceEntity> provinceEntities = new ArrayList<>(); //省份
    private List<List<DataInfoEntity>> cityname = new ArrayList<>(); //城市
    private List<EmotionEntity> emotionEntities = new ArrayList<>();// 情感状态
    private List<List<DataInfoEntity>> childEmotion = new ArrayList<>();  //情感子状态
    private List<GroupEntity> groupEntities = new ArrayList<>();  //年级，群组
    private List<List<DataInfoEntity>> childTag = new ArrayList<>(); //群组年级子状态
    private Map<Integer, SchoolInfoEntity> schoolMap = new HashMap<>();
    private List<SchoolInfoEntity> schoolInfoEntities = new ArrayList<>();
    private List<List<String>> yuanxi = new ArrayList<>();  //院系

    private OptionsPickerView pvOptions;
    private OptionsPickerView sexOptions;
    private int option = 0;//操作选择的内容
    private int birthDay;//出生年份
    private int nowYear;//当前年份
    private int mAge = -1; //年龄
    private int sex = -1;//性别
    private int gradeId; //年级
    private int emotionId; //感情状态
    private int cityId;  //省份城市
    private String mYx;  //院系
    private int schoolId;//学校
    private String realName;//真是姓名
    private String userName;//账号
    private int emotionOp1 = 0;//感情状态默认选则
    private int emotionOp2 = 0;
    private int cityOp1 = 0;  //所在地选择的位置
    private int cityOp2 = 0;
    private int gradeOp1 = 0; //年级选择的位置
    private int gradeOp2 = 0;
    private int schoolOp1 = 0;// 院系的选择的位置
    private int schoolOp2 = 0;
    private int uploadPhotoNum = 0;
    private boolean isUploadePhoto = false;

    private Handler loadSchoollHandler;
    private HandlerThread handlerThread;
    private LoadUserinfoAsync loadUserinfoAsync;

    private LoadUserinfoAsync createUserinfoAsync() {
        if (loadUserinfoAsync == null) {
            loadUserinfoAsync = new LoadUserinfoAsync(this);
        }
        return loadUserinfoAsync;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_change_mine_info;
    }

    @Override
    public void initView() {
        initToolBar();
        if (changeMineInfoPresenter == null) {
            changeMineInfoPresenter = new ChangeMineInfoPresenter(this);
            setPresenter(changeMineInfoPresenter);
        }
        getSupportLoaderManager().restartLoader(LoadUserinfoAsync.ASYNC_ID, null, this);
        loadSchoolCache();
        initPage();
        initData();
    }

    private void loadSchoolCache() {
        if (handlerThread == null) {
            handlerThread = new HandlerThread("loadSchool");
            handlerThread.start();
        }
        if (loadSchoollHandler == null) {
            loadSchoollHandler = new Handler(handlerThread.getLooper());
        }
        loadSchoollHandler.post(new Runnable() {
            @Override
            public void run() {
                String school = DataManager.getSchoolInfo();
                if (StringUtils.isNotEmpty(school)) {
                    SchoolDto schoolDto = JSON.parseObject(school, SchoolDto.class);
                    if (schoolDto != null && schoolDto.getData() != null) {
                        schoolMap.clear();
                        schoolMap.putAll(schoolDto.getData());
                    }
                }

                schoolInfoEntities.clear();
                schoolInfoEntities.addAll(DataManager.parseSchool(schoolMap));
                yuanxi.clear();
                for (SchoolInfoEntity schoolInfoEntity : schoolInfoEntities) {
                    yuanxi.add(schoolInfoEntity.getAcademic());
                }
                changeMineInfoPresenter.loadSchoolInfo();
            }
        });
    }

    private void initData() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            userEntity = (UserEntity) bundle.getSerializable("userEntity");
        }
        if (userEntity == null) {
            userEntity = UserManager.getUesrInfo(this);
        }
        initPickerView();
        if (userEntity != null) {
            text_photo.setText(userEntity.userMobile + "");
            inputAccount();
            inputRealName();
            showEmotion();
            showAddress();
            showGroup();
            showSchool();
            sex = userEntity.mSex;
            if (sex > 0) {
                text_sex.setText(sexList.get(sex - 1));
            } else {
                text_sex.setText("未设置");
            }
            if (StringUtils.isNotEmpty(userEntity.birthday)) {
                birthDay = MyTimeUtils.getBirthYear(userEntity.birthday);
                if (birthDay == 0) {
                    birthDay = Integer.valueOf(userEntity.birthday);
                }
                //对年份设置显示容错
                if (birthDay > 0) {
                    mAge = nowYear - birthDay;
                    text_birthday.setText(birthDay + "");
                } else {
                    text_birthday.setText("未设置");
                }
            } else {
                text_birthday.setText("未设置");
            }

            if (userEntity.school <= 0 && !StringUtils.isNotEmpty(userEntity.yuanxi)) {
                text_school.setText("未设置");
            }

            changeMineInfoPresenter.loadImageView(this, image_circle_photo,
                    userEntity.mUserImage, R.mipmap.image_mine_friend_avatar);
        }
    }

    private void initToolBar() {
        toolbar_title.setText("编辑资料");
        showToolBar(toolbar, true);
    }

    private void initPage() {
        image_circle_photo.setOnClickListener(this);
        view_set_sex.setOnClickListener(this);
        view_set_birth.setOnClickListener(this);
        view_set_emotion.setOnClickListener(this);
        view_set_address.setOnClickListener(this);
        view_set_grade.setOnClickListener(this);
        view_set_school.setOnClickListener(this);
        button_commit.setOnClickListener(this);
        sexList.add("男生");
        sexList.add("女生");
        nowYear = MyTimeUtils.getYearsNum(System.currentTimeMillis());
        int now = nowYear;
        for (int i = 0; i < 100; i++) {
            mYearsList.add(now--);
        }
    }

    private void changeEditStatus(EditText editText, boolean avaliable) {
        editText.setCursorVisible(avaliable);
        editText.setEnabled(avaliable);
    }

    private void inputAccount() {
        if (StringUtils.isNotEmpty(userEntity.userName)) {
            edit_user_account.setText(userEntity.userName + "");
            userName = userEntity.userName;
            changeEditStatus(edit_user_account, false);
        } else {
            edit_user_account.setHint("未设置");
            changeEditStatus(edit_user_account, true);
            edit_user_account.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {

                    userName = s.toString().replaceAll(" ", "");
                    if (userName.length() > 20) {
                        Toast.makeText(ChangeMineInfoActivity.this, "账号为2到20个以字母、数字、下划线和减号,必须以字母开头", Toast.LENGTH_SHORT).show();
                    }
                }
            });

        }
    }

    private void inputRealName() {
        if (StringUtils.isNotEmpty(userEntity.realname)) {
            edit_real_name.setText(userEntity.realname);
            realName = userEntity.realname;
            changeEditStatus(edit_real_name, true);
        } else {
            edit_real_name.setHint("未设置");
            changeEditStatus(edit_real_name, true);
        }
        edit_real_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                realName = s.toString().replaceAll(" ", "");
                if (realName.length() > 16) {
                    Toast.makeText(ChangeMineInfoActivity.this, "真实姓名不得多于16个字符！", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    private void initPickerView() {
        if (sexOptions == null) {
            sexOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    //返回的分别是三个级别的选中位置
                    switch (option) {
                        case pos_sex:
                            //1男2女
                            if (options1 == 0) {
                                sex = 1;
                            } else if (options1 == 1) {
                                sex = 2;
                            }
                            text_sex.setText(sexList.get(options1));
                            break;
                        case pos_age:
                            birthDay = mYearsList.get(options1);
                            text_birthday.setText(birthDay + "");
                            mAge = options1;
                            break;
                    }
                }
            }).setDividerColor(getResources().getColor(R.color.common_line))
                    .setTextColorCenter(getResources().getColor(R.color.str_color_black))
                    .setCancelColor(getResources().getColor(R.color.common_green))
                    .setSubmitColor(getResources().getColor(R.color.common_green))
                    .setSubCalSize(14)
                    .setContentTextSize(14)
                    .setTitleSize(14)
                    .setLineSpacingMultiplier(2f)
                    .setOutSideCancelable(false)
                    .build();
        }

        if (pvOptions == null) {
            pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    //返回的分别是三个级别的选中位置
                    switch (option) {
                        case pos_group:
                            DataInfoEntity group = groupEntities.get(options1).getChildTag().get(options2);
                            String groupStr = groupEntities.get(options1).getPickerViewText() + "  "
                                    + group.getName();
                            gradeId = group.id;
                            text_grade.setText(groupStr);
                            if (gradeId >= 10100 && gradeId <= 10109) {
                                view_set_school.setVisibility(View.VISIBLE);
                                line_grade.setVisibility(View.VISIBLE);
                                schoolId = userEntity.school;
                                mYx = userEntity.yuanxi;
                            } else {
                                //TODO 是否置空院校信息
//                                schoolId = 0;
//                                mYx = " ";
                                view_set_school.setVisibility(View.INVISIBLE);
                                line_grade.setVisibility(View.INVISIBLE);
                            }
                            gradeOp1 = options1;
                            gradeOp2 = options2;
                            break;
                        case pos_emotion:
                            DataInfoEntity emotion = emotionEntities.get(options1).getDataInfoEntities().get(options2);
                            String emotionStr = emotionEntities.get(options1).getPickerViewText() + "  " + emotion.getPickerViewText();
                            text_emotion.setText(emotionStr);
                            emotionId = emotion.id;
                            emotionOp1 = options1;
                            emotionOp2 = options2;
                            break;
                        case pos_city:
                            DataInfoEntity cityinfo = provinceEntities.get(options1).cityEntities.get(options2);
                            String cityname = provinceEntities.get(options1).getPickerViewText() + "  " + cityinfo.getPickerViewText();
                            text_address.setText(cityname);
                            cityId = cityinfo.id;
                            cityOp1 = options1;
                            cityOp2 = options2;
                            break;
                        case pos_school:
                            SchoolInfoEntity schoolInfoEntity = schoolInfoEntities.get(options1);
                            schoolId = schoolInfoEntity.id;
                            mYx = schoolInfoEntity.getAcademic().get(options2);
                            text_school.setText(schoolInfoEntity.getSchool() + "  " + mYx);
                            schoolOp1 = options1;
                            schoolOp2 = options2;
                            break;
                    }

                }
            }).setDividerColor(getResources().getColor(R.color.common_line))
                    .setTextColorCenter(getResources().getColor(R.color.str_color_black))
                    .setCancelColor(getResources().getColor(R.color.common_green))
                    .setSubmitColor(getResources().getColor(R.color.common_green))
                    .setSubCalSize(14)
                    .setContentTextSize(14)
                    .setLineSpacingMultiplier(2f)
                    .setTitleSize(14)
                    .setOutSideCancelable(false)
                    .build();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.image_circle_photo:
                setPhoto();
                break;
            case R.id.view_set_sex:
                option = pos_sex;
                sexOptions.setPicker(sexList);
                sexOptions.setTitleText("性别");
                sexOptions.show();
                if (sex > 0) {
                    sexOptions.setSelectOptions(sex - 1);
                }
                break;
            case R.id.view_set_birth:
                option = pos_age;
                sexOptions.setPicker(mYearsList);
//                LogUtil.e("yjl", "select:" + mAge);
                sexOptions.setTitleText("出生年份");
                sexOptions.show();
                if (mAge >= 0 && mAge < 100) {
                    sexOptions.setSelectOptions(mAge);
                }
                break;
            case R.id.view_set_emotion:
                //设置感情状态
                if (emotionEntities.size() > 0 && childEmotion.size() > 0) {
                    pvOptions.setTitleText("婚恋状态");
                    pvOptions.setPicker(emotionEntities, this.childEmotion);
                    pvOptions.show();
                    pvOptions.setSelectOptions(emotionOp1, emotionOp2);
                    option = pos_emotion;
                }
                break;
            case R.id.view_set_address:
                //设置所在地
                if (provinceEntities.size() > 0 && cityname.size() > 0) {
                    pvOptions.setTitleText("所在地区");
                    pvOptions.setPicker(provinceEntities, cityname);
                    pvOptions.setSelectOptions(cityOp1, cityOp2);
                    pvOptions.show();

                    option = pos_city;

                }
                break;
            case R.id.view_set_grade:
                //设置年级
                if (groupEntities.size() > 0 && childTag.size() > 0) {
                    pvOptions.setTitleText("我的年级");
                    pvOptions.setPicker(groupEntities, this.childTag);
                    pvOptions.setSelectOptions(gradeOp1, gradeOp2);
                    pvOptions.show();
                    option = pos_group;
                }
                break;
            case R.id.view_set_school:
                //设置学校
//                if (schoolInfoEntities.size() > 0 && yuanxi.size() > 0) {
//                    pvOptions.setTitleText("我的学校");
//                    pvOptions.setPicker(schoolInfoEntities, yuanxi);
//                    pvOptions.setSelectOptions(schoolOp1, schoolOp2);
//                    pvOptions.show();
//                    option = pos_school;
//                }
                Intent intent = new Intent(this, SearchSchoolActivity.class);
                startActivityForResult(intent, SearchSchoolActivity.request_from_editor_info);
                break;
            case R.id.button_commit:
                requestUpdateUserInfo();
                if (StringUtils.isNotEmpty(userName)
                        && !StringUtils.isNotEmpty(userEntity.userName)) {
                    //账号非必填
                    requestSetAccount();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SearchSchoolActivity.request_from_editor_info
                && resultCode == Activity.RESULT_OK) {

            SchoolInfoEntity selectSchool = (SchoolInfoEntity) data.getSerializableExtra("school");
            mYx = data.getStringExtra("yuanxi");
            text_school.setText(selectSchool.getSchool() + " - " + mYx);
            schoolId = selectSchool.getId();
        }
    }

    private void setPhoto() {
        final CropOptions cropOptions = CustomHelper.getCustomHelper().getCropOptions();
        final Uri imageUri = CustomHelper.getCustomHelper().getURI(getTakePhoto());//保存的路径
        if (choicePictureDialog == null) {
            choicePictureDialog = new ChoicePictureDialog(this);
            choicePictureDialog.choiceCameraPicture(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getTakePhoto().onPickFromCaptureWithCrop(imageUri, cropOptions);
                }
            });
            choicePictureDialog.choiceGallertPictire(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //从相册中获取图片
                    getTakePhoto().onPickFromGalleryWithCrop(imageUri, cropOptions);
                }
            });
        }
        if (!choicePictureDialog.isShowing()) {
            choicePictureDialog.show();
        }
    }

    private void showEmotion() {
        if (userEntity == null) {
            return;
        }
        if (userEntity.issingle > 0 && emotionEntities.size() > 0) {
            emotionId = userEntity.issingle;
            StringBuilder stringBuilder = new StringBuilder();
            EmotionEntity parentEmotion = null;
            DataInfoEntity childEmotion = null;
            for (int i = 0; i < emotionEntities.size(); i++) {
                EmotionEntity emotionEntity = emotionEntities.get(i);
                childEmotion = emotionEntity.getChildEmotion(userEntity.issingle);
                if (childEmotion != null) {
                    parentEmotion = emotionEntity;
                    emotionOp1 = i;
                    emotionOp2 = childEmotion.select;
                    break;
                }
            }
            if (parentEmotion != null) {
                stringBuilder.append(parentEmotion.emotion.getName() + "");
                if (childEmotion != null) {
                    stringBuilder.append("  ");
                }
            }
            if (childEmotion != null) {
                stringBuilder.append(childEmotion.getName());
            }
            if (stringBuilder.length() > 0) {
                text_emotion.setText(stringBuilder.toString());
            } else {
                text_emotion.setText("未设置");
            }
        } else {
            text_emotion.setText("未设置");
        }
    }

    private void showAddress() {
        if (userEntity == null) {
            return;
        }
        if (userEntity.address > 0 && provinceEntities.size() > 0) {
            cityId = userEntity.address;
            ProvinceEntity province = null;
            DataInfoEntity city = null;
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < provinceEntities.size(); i++) {
                ProvinceEntity provinceEntity = provinceEntities.get(i);
                city = provinceEntity.getCity(userEntity.address);
                if (city != null) {
                    cityOp1 = i;
                    cityOp2 = city.select;
                    province = provinceEntity;
                    break;
                }
            }
            if (province != null) {
                stringBuilder.append(province.province.getName() + "");
                if (city != null) {
                    stringBuilder.append("  ");
                }
            }
            if (city != null) {
                stringBuilder.append(city.getName() + "");
            }
            if (stringBuilder.length() > 0) {
                text_address.setText(stringBuilder.toString());
            } else {
                text_address.setText("未设置");
            }
        } else {
            text_address.setText("未设置");
        }
    }

    private void showGroup() {
        if (userEntity == null) {
            return;
        }
        if (userEntity.scholar > 0 && groupEntities.size() > 0) {
            gradeId = userEntity.scholar;
            GroupEntity groupEntity = null;
            DataInfoEntity childGroup = null;
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < groupEntities.size(); i++) {
                GroupEntity entity = groupEntities.get(i);
                childGroup = entity.getChildGroup(userEntity.scholar);
                if (childGroup != null) {
                    groupEntity = entity;
                    gradeOp1 = i;
                    gradeOp2 = childGroup.select;
                    break;
                }
            }
            if (groupEntity != null) {
                stringBuilder.append(groupEntity.mGroup.getName() + "");
                if (childGroup != null) {
                    stringBuilder.append("  ");
                }
            }
            if (childGroup != null) {
                stringBuilder.append(childGroup.getName() + "");
            }
            if (stringBuilder.length() > 0) {
                text_grade.setText(stringBuilder.toString());
            } else {
                text_grade.setText("未设置");
            }
        } else {
            text_grade.setText("未设置");
        }
    }

    private void showSchool() {
        if (userEntity == null) {
            return;
        }
        StringBuilder stringBuilder = new StringBuilder();
        SchoolInfoEntity schoolInfo = null;
        if (userEntity.school > 0 && schoolInfoEntities.size() > 0) {
            schoolId = userEntity.school;
            for (int i = 0; i < schoolInfoEntities.size(); i++) {
                SchoolInfoEntity schoolInfoEntity = schoolInfoEntities.get(i);
                if (schoolInfoEntity.getId() == userEntity.school) {
                    schoolInfo = schoolInfoEntity;
                    schoolOp1 = i;
                    break;
                }
            }
            if (schoolInfo != null) {
                stringBuilder.append(schoolInfo.getSchool());
                if (StringUtils.isNotEmpty(userEntity.yuanxi)) {
                    stringBuilder.append("  ");
                }
            }
        }
        schoolId = userEntity.school;
        mYx = userEntity.yuanxi;
        if (StringUtils.isNotEmpty(userEntity.yuanxi)) {
            mYx = userEntity.yuanxi;
            stringBuilder.append(userEntity.yuanxi);
            if (schoolInfo != null) {
                List<String> academic = schoolInfo.getAcademic();
                for (int i = 0; i < academic.size(); i++) {
                    if (userEntity.yuanxi.equalsIgnoreCase(academic.get(i))) {
                        schoolOp2 = i;
                    }
                }
            }
        }

        if (stringBuilder.length() > 0) {
            text_school.setText(stringBuilder.toString());
        } else {
            text_school.setText("未设置");
        }

        if (userEntity.scholar >= 10100 && userEntity.scholar <= 10109) {
            view_set_school.setVisibility(View.VISIBLE);
            line_grade.setVisibility(View.VISIBLE);
        } else {
            view_set_school.setVisibility(View.INVISIBLE);
            line_grade.setVisibility(View.INVISIBLE);
            return;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        StatusBarCompat.compat(this, Color.parseColor("#ffffff"));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getSupportLoaderManager().destroyLoader(LoadUserinfoAsync.ASYNC_ID);
        if (handlerThread != null) {
            handlerThread.quitSafely();
            handlerThread = null;
        }
        if (loadSchoollHandler != null) {
            loadSchoollHandler.removeCallbacksAndMessages(null);
            loadSchoollHandler = null;
        }
    }

    private void requestUplaodeImage() {
        if (TextUtils.isEmpty(photoPath)) {
            return;
        }
        isUploadePhoto = true;
        uploadPhotoNum++;
        Map param = new HashMap();
        param.put("Filedata", photoPath);
        changeMineInfoPresenter.upLoadPic(param);

    }

    /**
     * 更新用户账号
     */
    private void requestSetAccount() {
        if (StringUtils.isNotEmpty(userEntity.userName)) {
            return;
        }
        if (TextUtils.isEmpty(userName)
                || !StringUtils.isAccount(userName)) {
            Toast.makeText(this, "请设置唯一用户名,2至20个字母、数字、下划线和减号,必须以字母开头", Toast.LENGTH_SHORT).show();
            return;
        }
        if (UserManager.getUserLoginState(this)) {
            if (userEntity != null) {
                Map param = new HashMap();
                param.put("username", userName);
                changeMineInfoPresenter.loadSetAccountData(param);
            }

        }
    }

    /**
     * 更新用户信息
     */
    private void requestUpdateUserInfo() {

        if (realName.length() < 2 && realName.length() > 16) {
            Toast.makeText(this, "真实姓名不得少于2个或者多于16个字符！", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!StringUtils.checkChinese(realName)) {
            Toast.makeText(this, "真实姓名必须为中文！", Toast.LENGTH_SHORT).show();
            return;
        }
        if (sex < 0) {
            Toast.makeText(this, "请选择性别!", Toast.LENGTH_SHORT).show();
            return;
        }
        if (gradeId < 0) {
            Toast.makeText(this, "请设置身份信息!", Toast.LENGTH_SHORT).show();
            return;
        }
//        if (emotionId < 0) {
//            Toast.makeText(this, "请选择感情状态!", Toast.LENGTH_SHORT).show();
//            return;
//        }
        if (cityId < 0) {
            Toast.makeText(this, "请选择城市地址!", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mAge <= 0) {
            Toast.makeText(this, "请设置出生年份!", Toast.LENGTH_SHORT).show();
            return;
        } else if (mAge < 8) {
            Toast.makeText(this, "您的年龄太小!", Toast.LENGTH_SHORT).show();
            return;
        } else if (mAge >= 100) {
            Toast.makeText(this, "您的年龄太大!", Toast.LENGTH_SHORT).show();
            return;
        }

        if (gradeId >= 10100 && gradeId <= 10109) {
            if (schoolId <= 0) {
                Toast.makeText(this, "请选择学校!", Toast.LENGTH_SHORT).show();
                return;
            }
            if (!StringUtils.isNotEmpty(mYx)) {

                Toast.makeText(this, "请选择专业!", Toast.LENGTH_SHORT).show();
                return;
            }

        }

        if (StringUtils.isNotEmpty(realName)) {
            userEntity.realname = realName;
        }
        this.userEntity.mSex = this.sex;
        this.userEntity.scholar = gradeId;
        this.userEntity.issingle = emotionId;
        this.userEntity.address = cityId;
        this.userEntity.school = schoolId;
        this.userEntity.yuanxi = mYx;
        if (birthDay > 0) {
            this.userEntity.birthday = birthDay + "";
        }
        changeMineInfoPresenter.loadUpdateUserinfoData(this.userEntity);
    }

    @Override
    public void takeSuccess(final TResult result) {
        if (result != null && result.getImage() != null) {
            if (choicePictureDialog != null) {
                choicePictureDialog.dismiss();
            }
            photoPath = result.getImage().getCompressPath();
            tempPhoto = result.getImage().getOriginalPath();
            final Bitmap bitmap = BitmapFactory.decodeFile(photoPath);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    LogUtil.e("yjl", "takeSuccess:" + result.getImage().getCompressPath());
                    image_circle_photo.setImageBitmap(bitmap);
                }
            });
            requestUplaodeImage();
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {
        if (choicePictureDialog != null) {
            choicePictureDialog.dismiss();
        }
    }

    @Override
    public void takeCancel() {
        if (choicePictureDialog != null) {
            choicePictureDialog.dismiss();
        }
    }

    @Override
    public Loader<DataDto> onCreateLoader(int id, Bundle args) {
        return createUserinfoAsync();
    }

    @Override
    public void onLoadFinished(Loader<DataDto> loader, DataDto data) {
        getSupportLoaderManager().destroyLoader(LoadUserinfoAsync.ASYNC_ID);
        if (data.getEmotion() != null) {
            emotionEntities.clear();
            emotionEntities.addAll(DataManager.parseEmotion(data.getEmotion()));
            childEmotion.clear();
            for (EmotionEntity emotionEntity : emotionEntities) {
                childEmotion.add(emotionEntity.dataInfoEntities);
            }
            showEmotion();
        }

        if (data.getCitys() != null) {
            provinceEntities.clear();
            provinceEntities.addAll(DataManager.parseCityData(data.getCitys()));
            cityname.clear();
            for (ProvinceEntity provinceEntity : provinceEntities) {
                cityname.add(provinceEntity.cityEntities);
            }
            showAddress();
        }

        if (data.getGroup() != null) {
            groupEntities.clear();
            groupEntities.addAll(DataManager.parseGroupData(data.getGroup()));
            childTag.clear();
            for (GroupEntity groupEntity : groupEntities) {
                childTag.add(groupEntity.childTag);
            }
            showGroup();
        }
    }

    @Override
    public void onLoaderReset(Loader<DataDto> loader) {

    }

    @Override
    public void updateSetPhotoView(String photoUrl) {
        if (!TextUtils.isEmpty(photoUrl)) {
            isUploadePhoto = false;
            userEntity.mUserImage = photoUrl;
            UserManager.saveUserInfo(this, userEntity);
            Toast.makeText(this, "头像设置成功!", Toast.LENGTH_SHORT).show();
            changeMineInfoPresenter.clearImageCache(ServerManager.getImageUrl() + photoUrl);
            try {
                File photo = new File(photoPath);
                if (photo.exists()) {
                    photo.delete();
                }
                File originPhoto = new File(tempPhoto);
                if (originPhoto.exists()) {
                    originPhoto.delete();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            setResult(MineInfoActivity.RESULT_SUCCESS_PHOTO, getIntent());
        }
    }

    @Override
    public void showErrorData(NetworkManager.ResultCode resultCode, String msg) {
        super.showErrorData(resultCode, msg);
        if (isUploadePhoto && StringUtils.isNotEmpty(photoPath) && uploadPhotoNum < 3) {
            requestUplaodeImage();
        }
    }

    @Override
    public void updateSchoolInfo(Map<Integer, SchoolInfoEntity> school) {
        if (school != null && !school.isEmpty()) {
            this.schoolMap.clear();
            this.schoolMap.putAll(school);
            schoolInfoEntities.clear();
            schoolInfoEntities.addAll(DataManager.parseSchool(this.schoolMap));
            yuanxi.clear();
            for (SchoolInfoEntity schoolInfoEntity : schoolInfoEntities) {
                yuanxi.add(schoolInfoEntity.getAcademic());
            }
            showSchool();

        }
    }

    @Override
    public void updateUserInfoView(UserEntity userEntity) {
        if (userEntity != null) {
            this.userEntity.updateUserEntity(userEntity);
            UserManager.saveUserInfo(this, userEntity);
            if (StringUtils.isNotEmpty(userEntity.userName)) {
                inputAccount();
            }
            Toast.makeText(this, "设置成功！", Toast.LENGTH_SHORT).show();
            setResult(MineInfoActivity.RESULT_SUCCESS_INFO, getIntent());
           /* //通知更新了用户信息
            EventEntity eventEntity = new EventEntity();
            eventEntity.eventId = EventManager.EVENT_UPDATE_USERINFO;
            eventEntity.eventName = "update_user_info";
            EventBus.getDefault().post(eventEntity);*/
        }
    }

    @Override
    public void updateSetAccountView(NetworkManager.ResultCode resultCode, String msg) {
        //设置账号
        if (NetworkManager.ResultCode.RESULT_SUCCESS.equals(resultCode)) {
            Toast.makeText(this, "账号设置成功!", Toast.LENGTH_SHORT).show();
            userEntity.userName = userName;
            edit_user_account.setText(userName);
            UserManager.saveUserInfo(this, userEntity);
            inputAccount();
            setResult(MineInfoActivity.RESULT_SUCCESS_ACCOUNT, getIntent());
        }
    }
}
